package com.winit.schedule.job.tracker.channel;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ChannelManager {

    private static final Logger                                                         LOGGER                      = LoggerFactory.getLogger(ChannelManager.class);

    // 任务节点列表
    private static final ConcurrentHashMap<String/* taskTrackerUuid */, ChannelWrapper> channelMap       = new ConcurrentHashMap<String, ChannelWrapper>();

    // 用来定时检查已经关闭的channel
    private static final ScheduledExecutorService                                       channelCheckExecutorService = Executors.newScheduledThreadPool(1);

    static {

        channelCheckExecutorService.scheduleWithFixedDelay(new Runnable() {

            @Override
            public void run() {
                checkCloseChannel(channelMap);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("TaskTracker Channel Pool " + channelMap);
                }

            }
        }, 10, 30, TimeUnit.SECONDS);
    }

    private ChannelManager(){
    }

    /**
     * 检查 关闭的channel
     * 
     * @param channelMap
     */
    private static void checkCloseChannel(ConcurrentHashMap<String, ChannelWrapper> channelMap) {
        String[] channelKeys = channelMap.keySet().toArray(new String[] {});

        for (String channelKey : channelKeys) {
            ChannelWrapper channel = channelMap.get(channelKey);
            if (channel.isClosed()) {
                channelMap.remove(channelKey);
            }
        }
    }

    public static ChannelWrapper getChannel(String taskTrackerUuid) {
        return channelMap.get(taskTrackerUuid);
    }

    /**
     * 添加channel
     * 
     * @param channel
     */
    public static void addChannel(ChannelWrapper channel) {
        channelMap.putIfAbsent(channel.getTaskTrackerUuid(), channel);
    }

    public static void removeChannel(String taskTrackerUuid) {
        ChannelWrapper channel = getChannel(taskTrackerUuid);
        if (channel != null) {
            channelMap.remove(taskTrackerUuid);
            LOGGER.info("remove channel={}", channel);
        }
    }
}
